import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Separator } from '@/components/ui/separator';
import { 
  ArrowLeft, 
  MapPin, 
  CreditCard, 
  Smartphone,
  Banknote
} from 'lucide-react';
import { orderApi } from '@/db/api';
import { useAuth } from 'miaoda-auth-react';
import type { CartItem, ShippingAddress, CheckoutFormData } from '@/types/types';
import { toast } from 'sonner';

const Checkout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { user } = useAuth();
  
  const cartItems = location.state?.cartItems as CartItem[] || [];
  
  const [loading, setLoading] = useState(false);
  const [shippingAddress, setShippingAddress] = useState<ShippingAddress>({
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    address: '',
    postal_code: ''
  });
  const [paymentMethod, setPaymentMethod] = useState('wechat');
  const [notes, setNotes] = useState('');

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    
    if (cartItems.length === 0) {
      toast.error('没有选择商品');
      navigate('/cart');
      return;
    }
  }, [user, cartItems, navigate]);

  const totalAmount = cartItems.reduce((sum, item) => {
    return sum + (item.product?.price || 0) * item.quantity;
  }, 0);

  const handleAddressChange = (field: keyof ShippingAddress, value: string) => {
    setShippingAddress(prev => ({ ...prev, [field]: value }));
  };

  const validateForm = () => {
    if (!shippingAddress.name.trim()) {
      toast.error('请输入收货人姓名');
      return false;
    }
    if (!shippingAddress.phone.trim()) {
      toast.error('请输入收货人手机号');
      return false;
    }
    if (!/^1[3-9]\d{9}$/.test(shippingAddress.phone)) {
      toast.error('请输入正确的手机号');
      return false;
    }
    if (!shippingAddress.province.trim()) {
      toast.error('请输入省份');
      return false;
    }
    if (!shippingAddress.city.trim()) {
      toast.error('请输入城市');
      return false;
    }
    if (!shippingAddress.district.trim()) {
      toast.error('请输入区县');
      return false;
    }
    if (!shippingAddress.address.trim()) {
      toast.error('请输入详细地址');
      return false;
    }
    return true;
  };

  const handleSubmitOrder = async () => {
    if (!validateForm()) return;

    try {
      setLoading(true);
      
      const checkoutData: CheckoutFormData = {
        shipping_address: shippingAddress,
        payment_method: paymentMethod,
        notes: notes.trim() || undefined
      };

      const order = await orderApi.createOrder(checkoutData, cartItems);
      
      toast.success('订单创建成功！');
      navigate(`/orders/${order.id}`);
    } catch (error) {
      console.error('创建订单失败:', error);
      toast.error('创建订单失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (cartItems.length === 0) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="flex items-center gap-4 mb-8">
          <Button variant="ghost" onClick={() => navigate('/cart')}>
            <ArrowLeft className="h-5 w-5 mr-2" />
            返回购物车
          </Button>
          <h1 className="text-3xl font-bold text-gray-900">确认订单</h1>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Order Form */}
          <div className="lg:col-span-2 space-y-6">
            {/* Shipping Address */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <MapPin className="h-5 w-5" />
                  收货地址
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="name">收货人姓名 *</Label>
                    <Input
                      id="name"
                      value={shippingAddress.name}
                      onChange={(e) => handleAddressChange('name', e.target.value)}
                      placeholder="请输入收货人姓名"
                    />
                  </div>
                  <div>
                    <Label htmlFor="phone">手机号码 *</Label>
                    <Input
                      id="phone"
                      value={shippingAddress.phone}
                      onChange={(e) => handleAddressChange('phone', e.target.value)}
                      placeholder="请输入手机号码"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="province">省份 *</Label>
                    <Input
                      id="province"
                      value={shippingAddress.province}
                      onChange={(e) => handleAddressChange('province', e.target.value)}
                      placeholder="省份"
                    />
                  </div>
                  <div>
                    <Label htmlFor="city">城市 *</Label>
                    <Input
                      id="city"
                      value={shippingAddress.city}
                      onChange={(e) => handleAddressChange('city', e.target.value)}
                      placeholder="城市"
                    />
                  </div>
                  <div>
                    <Label htmlFor="district">区县 *</Label>
                    <Input
                      id="district"
                      value={shippingAddress.district}
                      onChange={(e) => handleAddressChange('district', e.target.value)}
                      placeholder="区县"
                    />
                  </div>
                </div>

                <div>
                  <Label htmlFor="address">详细地址 *</Label>
                  <Input
                    id="address"
                    value={shippingAddress.address}
                    onChange={(e) => handleAddressChange('address', e.target.value)}
                    placeholder="请输入详细地址"
                  />
                </div>

                <div>
                  <Label htmlFor="postal_code">邮政编码</Label>
                  <Input
                    id="postal_code"
                    value={shippingAddress.postal_code}
                    onChange={(e) => handleAddressChange('postal_code', e.target.value)}
                    placeholder="邮政编码（可选）"
                  />
                </div>
              </CardContent>
            </Card>

            {/* Payment Method */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <CreditCard className="h-5 w-5" />
                  支付方式
                </CardTitle>
              </CardHeader>
              <CardContent>
                <RadioGroup value={paymentMethod} onValueChange={setPaymentMethod}>
                  <div className="flex items-center space-x-2 p-4 border rounded-lg">
                    <RadioGroupItem value="wechat" id="wechat" />
                    <Label htmlFor="wechat" className="flex items-center gap-2 cursor-pointer">
                      <Smartphone className="h-5 w-5 text-green-600" />
                      微信支付
                    </Label>
                  </div>
                  <div className="flex items-center space-x-2 p-4 border rounded-lg">
                    <RadioGroupItem value="alipay" id="alipay" />
                    <Label htmlFor="alipay" className="flex items-center gap-2 cursor-pointer">
                      <Smartphone className="h-5 w-5 text-blue-600" />
                      支付宝
                    </Label>
                  </div>
                  <div className="flex items-center space-x-2 p-4 border rounded-lg">
                    <RadioGroupItem value="bank" id="bank" />
                    <Label htmlFor="bank" className="flex items-center gap-2 cursor-pointer">
                      <CreditCard className="h-5 w-5 text-gray-600" />
                      银行卡支付
                    </Label>
                  </div>
                  <div className="flex items-center space-x-2 p-4 border rounded-lg">
                    <RadioGroupItem value="cod" id="cod" />
                    <Label htmlFor="cod" className="flex items-center gap-2 cursor-pointer">
                      <Banknote className="h-5 w-5 text-orange-600" />
                      货到付款
                    </Label>
                  </div>
                </RadioGroup>
              </CardContent>
            </Card>

            {/* Order Notes */}
            <Card>
              <CardHeader>
                <CardTitle>订单备注</CardTitle>
              </CardHeader>
              <CardContent>
                <Textarea
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  placeholder="如有特殊要求，请在此留言（可选）"
                  rows={3}
                />
              </CardContent>
            </Card>
          </div>

          {/* Order Summary */}
          <div className="lg:col-span-1">
            <Card className="sticky top-8">
              <CardHeader>
                <CardTitle>订单详情</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* Order Items */}
                <div className="space-y-3">
                  {cartItems.map((item) => (
                    <div key={item.id} className="flex items-center gap-3">
                      <div className="w-16 h-16 flex-shrink-0 overflow-hidden rounded-lg">
                        <img
                          src={item.product?.images?.[0] || 'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=200'}
                          alt={item.product?.name}
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-medium text-gray-900 truncate">
                          {item.product?.name}
                        </div>
                        <div className="text-xs text-gray-500">
                          {item.size && `${item.size} `}
                          {item.color && `${item.color} `}
                          × {item.quantity}
                        </div>
                        <div className="text-sm font-medium text-pink-600">
                          ¥{((item.product?.price || 0) * item.quantity).toFixed(2)}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>

                <Separator />

                {/* Price Summary */}
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span>商品总价</span>
                    <span>¥{totalAmount.toFixed(2)}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span>运费</span>
                    <span className="text-green-600">免费</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span>优惠券</span>
                    <span>-¥0.00</span>
                  </div>
                </div>

                <Separator />

                <div className="flex justify-between text-lg font-bold">
                  <span>应付金额</span>
                  <span className="text-pink-600">¥{totalAmount.toFixed(2)}</span>
                </div>

                <Button
                  onClick={handleSubmitOrder}
                  disabled={loading}
                  className="w-full bg-pink-600 hover:bg-pink-700"
                  size="lg"
                >
                  {loading ? '提交中...' : '提交订单'}
                </Button>

                <div className="text-xs text-gray-500 text-center">
                  点击"提交订单"表示您同意我们的服务条款
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Checkout;